<?php
namespace Api\Service;

/**
 * 文章/资讯
 */
class ArticleService
{
    // 分页数量
    const PAGET_NUMBER = 2;
    /**
     * 用户提交意见/意见
     * @param [type] $user_id [description]
     * @param [type] $content [description]
     */
    public function detail($id)
    {
        $article = M('article')
            ->alias('a')
            ->field('a.id,c.name,a.title,a.image,a.description,a.add_time')
            ->join('__ARTICLE_CATEGORY__ c on a.category_id = c.id')
            ->where([
                'a.is_delete' => 0,
                'a.id'        => $id,
            ])->find();

        return $article ? $article : [];
    }

    /**
     * 资讯分类
     * @return [type] [description]
     */
    public function category()
    {
        $category = S('article_category');
        if (!$category || true) {

            $category = M('article_category')
                ->field('id,name')
                ->where(['is_delete' => 0])
                ->order('sort desc, id desc')
                ->select();

            S('article_category', $category, 3600); // 一个小时
        }
        return $category ? $category : [];
    }

    /**
     * 查找
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function search($data)
    {
        $where = [
            'a.is_delete' => 0,
        ];

        // 分类查找
        if (isset($data['category_id']) && $data['category_id']) {
            $where['a.category_id'] = $data['category_id'];
        }

        $count = M('article')->alias('a')->where($where)->count();
        if ($count) {
            $page    = ceil($count / self::PAGET_NUMBER);
            $article = M('article')
                ->alias('a')
                ->field('a.id,c.name,a.title,a.image,a.description,a.add_time')
                ->join('__ARTICLE_CATEGORY__ c on a.category_id = c.id')
                ->where($where)
                ->order('a.sort desc, a.id desc')
                ->page($data['page'], self::PAGET_NUMBER)
                ->select();
        }

        return [
            'count'    => intval($count),
            'cur_page' => intval($data['page']),
            'page'     => $page ? $page : 0,
            'data'     => $article ? $article : [],
        ];
    }

    /**
     * 获取排序最大的文章
     * @return [type] [description]
     */
    public function top()
    {
        $article = S('top_article');
        if (!$article || true) {
            $article = M('article')
                ->alias('a')
                ->field('a.id,c.name,a.title,a.image,a.description,a.add_time')
                ->join('__ARTICLE_CATEGORY__ c on a.category_id = c.id')
                ->where(['a.is_delete' => 0])
                ->find();
            S('top_article', $article, 3600); // 一个小时
        }
        return $article;
    }
}
